<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BrowserRouter 的实现原理</title>
    <style>
        #result{
            width: 400px;
            height: 300px;
            border:solid 1px #999;
        }
    </style>
</head>
<body>
    <a href="/home">Home</a>
    <a href="/about">About</a>

    <div id="result">

    </div>

    <script>
        //获取所有的 a 链接
        let links = document.querySelectorAll('a');
        //遍历所有
        links.forEach(link => {
            //绑定单击事件
            link.onclick = function(e){
                //阻止默认行为
                e.preventDefault();
                //修改网页的 URL , 并且页面不更新
                history.pushState({id: 100}, '', e.target.href);
                //根据 url 的路径修改 result 的显示内容
                switch(location.pathname){
                    case '/home':
                        result.innerHTML = '首页 Home Home Home';
                        break;
                    case '/about':
                        result.innerHTML = '关于我们 about about about';
                        break;
                }
            }
        });

        window.addEventListener('popstate', () => {
            //根据 url 的路径修改 result 的显示内容
            switch(location.pathname){
                case '/home':
                    result.innerHTML = '首页 Home Home Home';
                    break;
                case '/about':
                    result.innerHTML = '关于我们 about about about';
                    break;
            }
        })

    </script>
</body>
</html>